﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DosciWordPlugin.Models;
using System.IO;
using Newtonsoft.Json;

namespace DosciWordPlugin.Common
{
    public static class CacheManager
    {
        private static string FILE_USER = "";
        public static readonly string DATA_FOLDER = "";

        static CacheManager() 
        {
            DATA_FOLDER = System.Windows.Forms.Application.UserAppDataPath + "/DosciData/";
            FILE_USER = DATA_FOLDER + "user.dat";
            if (!Directory.Exists(DATA_FOLDER))
                Directory.CreateDirectory(DATA_FOLDER);
        }

        public static User UserInfo
        {
            get;
            private set;
        }

        public static List<string> CitationStyleList = new List<string>();
        public static List<TemplateModel> TemplateList = new List<TemplateModel>();

        public static void Init()
        {
            try
            {
                string dataFolder = DATA_FOLDER;

                if (!Directory.Exists(dataFolder))
                    Directory.CreateDirectory(dataFolder);

                // user
                if (File.Exists(FILE_USER))
                {
                    string userInfoStr = File.ReadAllText(FILE_USER, Encoding.UTF8);
                    if (!string.IsNullOrEmpty(userInfoStr))
                        UserInfo = JsonConvert.DeserializeObject<User>(userInfoStr);
                }

                var dotFolder = new DirectoryInfo(dataFolder);
                foreach (var dotFile in dotFolder.GetFiles())
                {
                    if (dotFile.Extension != ".dot")
                        continue;
                    string[] idName = dotFile.Name.Split(new string[] { "___" }, StringSplitOptions.RemoveEmptyEntries);
                    if (idName.Length != 2) continue;

                    TemplateModel templateModel = new TemplateModel
                    {
                        ID = idName[0],
                        Name = idName[1].Replace(".dot", ""),
                        LocalFilePath = dotFile.FullName,
                    };

                    TemplateList.Add(templateModel);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
        }
        
        public static void SetUserInfo(User user) 
        {
            try
            {
                string str = "";
                if (user != null)
                {
                    str = JsonConvert.SerializeObject(user);
                }
                
                File.WriteAllText(FILE_USER, str);  // 写入 IO 缓存
                UserInfo = user;    // 设置当前用户
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
        }
    }
}
